import Router from '@koa/router';
import Koa from 'koa';
import { BaseRouter } from './base.router';
import UserRouter from './user.router';
import { ResponseUtil } from '@/utils/response';
import { healthCheck } from '@/middlewares';

/**
 * 路由管理器
 */
export class RouteManager {
  private app: Koa;
  private mainRouter: Router;
  private routers: BaseRouter[] = [];

  constructor(app: Koa) {
    this.app = app;
    this.mainRouter = new Router();
    this.setupRoutes();
  }

  /**
   * 设置所有路由
   */
  private setupRoutes(): void {
    // 添加健康检查中间件
    this.app.use(healthCheck);

    // 创建路由实例
    const userRouter = new UserRouter();

    // 注册路由
    this.routers.push(userRouter);

    // 应用路由到主应用
    this.routers.forEach(router => {
      this.app.use(router.routes());
      this.app.use(router.allowedMethods());
    });

    // 设置根路由和API信息
    this.setupRootRoutes();
    
    // 设置API版本路由
    this.setupVersionRoutes();
  }

  /**
   * 设置根路由
   */
  private setupRootRoutes(): void {
    /**
     * @swagger
     * /:
     *   get:
     *     tags:
     *       - 系统信息
     *     summary: 获取 API 服务信息
     *     description: 获取 API 服务的基本信息和可用端点
     *     responses:
     *       200:
     *         description: 服务信息获取成功
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: object
     *                       properties:
     *                         name:
     *                           type: string
     *                           description: 服务名称
     *                         version:
     *                           type: string
     *                           description: 服务版本
     *                         description:
     *                           type: string
     *                           description: 服务描述
     *                         environment:
     *                           type: string
     *                           description: 运行环境
     *                         timestamp:
     *                           type: string
     *                           format: date-time
     *                           description: 当前时间
     *                         uptime:
     *                           type: number
     *                           description: 服务运行时间(秒)
     *                         endpoints:
     *                           type: object
     *                           description: 可用的端点
     */
    this.mainRouter.get('/', (ctx) => {
      ctx.status = 200;
      ctx.body = ResponseUtil.success({
        name: 'JMTemp Server API',
        version: '1.0.0',
        description: '基于 Node.js 的后端 API 项目脚手架',
        environment: process.env.NODE_ENV,
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        endpoints: {
          health: '/health',
          api: '/api/v1',
          documentation: '/api-docs',
        },
      }, '欢迎使用 JMTemp Server API');
    });

    /**
     * @swagger
     * /health:
     *   get:
     *     tags:
     *       - 系统信息
     *     summary: 健康检查
     *     description: 检查 API 服务的健康状态和系统信息
     *     responses:
     *       200:
     *         description: 服务正常运行
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: object
     *                       properties:
     *                         status:
     *                           type: string
     *                           enum: [ok]
     *                           description: 服务状态
     *                         timestamp:
     *                           type: string
     *                           format: date-time
     *                           description: 当前时间
     *                         uptime:
     *                           type: number
     *                           description: 服务运行时间(秒)
     *                         memory:
     *                           type: object
     *                           description: 内存使用情况
     *                         version:
     *                           type: string
     *                           description: Node.js 版本
     *       503:
     *         description: 服务不可用
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ErrorResponse'
     */
    // 健康检查在 healthCheck 中间件中处理

    /**
     * @swagger
     * /api:
     *   get:
     *     tags:
     *       - 系统信息
     *     summary: 获取 API 信息
     *     description: 获取 API 的版本信息和可用端点
     *     responses:
     *       200:
     *         description: API 信息获取成功
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: object
     *                       properties:
     *                         version:
     *                           type: string
     *                           description: 当前 API 版本
     *                         currentVersion:
     *                           type: string
     *                           description: 当前版本路径
     *                         availableVersions:
     *                           type: array
     *                           items:
     *                             type: string
     *                           description: 可用的 API 版本
     *                         documentation:
     *                           type: string
     *                           description: API 文档路径
     *                         endpoints:
     *                           type: object
     *                           description: 可用的端点
     */
    // API 根路径
    this.mainRouter.get('/api', (ctx) => {
      ctx.status = 200;
      ctx.body = ResponseUtil.success({
        version: 'v1',
        currentVersion: '/api/v1',
        availableVersions: ['/api/v1'],
        documentation: '/api-docs',
        endpoints: {
          users: '/api/v1/users',
        },
      }, 'API 信息');
    });

    this.app.use(this.mainRouter.routes());
    this.app.use(this.mainRouter.allowedMethods());
  }

  /**
   * 设置API版本路由
   */
  private setupVersionRoutes(): void {
    const v1Router = new Router({ prefix: '/api/v1' });

    // API v1 信息
    v1Router.get('/', (ctx) => {
      ctx.status = 200;
      ctx.body = ResponseUtil.success({
        version: 'v1',
        status: 'stable',
        documentation: '/api-docs',
        resources: {
          users: {
            path: '/api/v1/users',
            methods: ['GET', 'POST', 'PUT', 'DELETE'],
            description: '用户管理',
          },
        },
        rateLimit: {
          standard: '100 requests per 15 minutes',
          strict: '5 requests per 15 minutes',
          login: '5 requests per 15 minutes',
        },
      }, 'API v1 信息');
    });

    this.app.use(v1Router.routes());
    this.app.use(v1Router.allowedMethods());
  }

  /**
   * 获取所有路由信息
   */
  public getRouteInfo(): Array<{ path: string; methods: string[]; description?: string }> {
    const routes: Array<{ path: string; methods: string[]; description?: string }> = [];

    this.routers.forEach(router => {
      const routerInstance = router.getRouter();
      routerInstance.stack.forEach((layer: any) => {
        routes.push({
          path: layer.path,
          methods: layer.methods,
          description: layer.name || '',
        });
      });
    });

    return routes;
  }

  /**
   * 打印路由信息
   */
  public printRoutes(): void {
    console.log('\n=== 已注册的路由 ===');
    
    this.routers.forEach(router => {
      const routerInstance = router.getRouter();
      const routerName = router.constructor.name;
      
      console.log(`\n${routerName}:`);
      
      routerInstance.stack.forEach((layer: any) => {
        const methods = layer.methods.join(', ');
        console.log(`  ${methods.padEnd(20)} ${layer.path}`);
      });
    });
    
    console.log('\n===================\n');
  }

  /**
   * 获取路由统计信息
   */
  public getRouteStats(): {
    totalRoutes: number;
    routerCount: number;
    methodCounts: Record<string, number>;
  } {
    let totalRoutes = 0;
    const methodCounts: Record<string, number> = {};

    this.routers.forEach(router => {
      const routerInstance = router.getRouter();
      routerInstance.stack.forEach((layer: any) => {
        totalRoutes++;
        layer.methods.forEach((method: string) => {
          methodCounts[method] = (methodCounts[method] || 0) + 1;
        });
      });
    });

    return {
      totalRoutes,
      routerCount: this.routers.length,
      methodCounts,
    };
  }
}

// 导出路由类
export { BaseRouter } from './base.router';
export { default as UserRouter } from './user.router';

/**
 * 初始化路由
 */
export const initializeRoutes = (app: Koa): RouteManager => {
  const routeManager = new RouteManager(app);
  
  // 在开发环境下打印路由信息
  if (process.env.NODE_ENV === 'development') {
    routeManager.printRoutes();
  }
  
  return routeManager;
};

export default RouteManager;